import {createStore} from 'vuex'
import {getStore, removeStore, setStore} from '@/plugins/cache'


// 创建一个新的 store 实例
const store = createStore({
    state() {
        return {
            Token: "",
            UserData: {},
            websocket: null,// socket对象
            timer: null,// 心跳检测
            timeout: 60000,// 心跳检测频率
            socketMessage: '',// socket接收的消息体
            routeStoreList: [],// 需要缓存的页面地址
            pageInfo: []
        }
    },
    getters: {
        getToken(state) {
            return state.Token;
        },
        getUserData(state) {
            return state.UserData;
        },
        loginStatus(state, getters) {
            // 登录状态
            return Boolean(getters.getToken && getters.getUserData);
        },
        routeStoreList(state) {
            return state.routeStoreList;
        },
        pageInfo(state) {
            return state.pageInfo;
        }
    },
    mutations: {
        addPage(state, data) {
            state.pageInfo.push(data);
        },
        destroyPage(state) {
            state.pageInfo = [];
        },
        addRouteStoreList(state, name) {
            // 添加需要缓存的路由名称并保存至vuex
            if (!state.routeStoreList.find(item => {
                return item == name;
            })) {
                // 如果不存在则添加
                state.routeStoreList.push(name);
            }
        },
        deleteouteStoreList(state, name) {
            // 删除缓存的页面名称
            let storeIndex = state.routeStoreList.indexOf(name);
            if (storeIndex !== -1) {
                state.routeStoreList.splice(storeIndex, 1);
            }
        },
        UpdateLoginStatus(state, data) {
            if (data.Token) {
                state.Token = data.Token;
                setStore({
                    name: 'Token',
                    content: data.Token
                })
            }
            if (data.UserData) {
                state.UserData = data.UserData;
                setStore({
                    name: 'UserData',
                    content: data.UserData
                })
            }
        },
        createWebSocket(state, url) {
            // 创建socket 并存入vuex
            let option = encodeURIComponent(state.Token);
            state.websocket = new WebSocket(url, [option]);
            state.websocket.onclose = (e) => {
                clearInterval(state.timer);
                console.log(e, "自动断开连接");
            };
            state.websocket.onopen = (e) => {
                // console.log(e, "连接成功");
                state.timer = setInterval(() => {
                    state.websocket.send("PING");
                }, state.timeout);
            };
            state.websocket.onerror = (e) => {
                console.log(e, "连接失败");
            };
            state.websocket.onmessage = (e) => {
                console.log(e, "收到消息");
                state.socketMessage = e.data;
            };
        },
        socketSend(state, data) {
            // 发送消息
            state.websocket.send(JSON.stringify(data));
        },
        logout(state, next) {
            // 退出登录 next为回调函数
            state.Token = "";
            state.UserData = {};
            removeStore({
                name: 'Token'
            })
            removeStore({
                name: 'UserData'
            })
            state.websocket.close();
            clearInterval(state.timer);
            next();
        }
    },
    actions: {
        getAssignPage({state}, name: any): object {
            console.log(state)
            let app = state.pageInfo.find(item => {
                console.log(item.$options)
                return item.$options.name == name
            });
            return app ? app.$.devtoolsRawSetupState : {};
        },
        UpdateLoginStatus(context, data) {
            // 更新登录状态
            context.commit('UpdateLoginStatus', data);
            context.commit('createWebSocket', import.meta.env.VITE_WEBSOCKET_URL)
        },
        InitLoginStatus(context) {
            // 初始化登录状态
            context.commit('UpdateLoginStatus', {
                Token: getStore({
                    name: 'Token'
                }),
                UserData: getStore({
                    name: 'UserData'
                })
            });
        },

    }
})


export default store;
